/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package portal.system.inzerat;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Riso-Desktop
 */
@WebServlet(name = "VypisInzeratov", urlPatterns = {"/inzeraty"})
public class VypisInzeratov extends HttpServlet {

    PrintWriter out;
    String driver = portal.constants.Database.DATABASE_DRIVER;
    Connection con = null;
    Statement stmt = null;
    private ResultSet rs = null;
    String userName = portal.constants.Database.DATABASE_USER;
    String password = portal.constants.Database.DATABASE_PASSWORD;
    String URL = portal.constants.Database.DATABASE_URL;
    HttpSession session;

    @Override
    public void init() {
        try {
            super.init();
            Class.forName(driver);
            con = DriverManager.getConnection(URL, userName, password);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public synchronized int VypisInzeraty(HttpServletRequest request, HttpServletResponse response) {
        String podkategoria = request.getParameter("podkategoria");
        String kategoria = request.getParameter("kategoria");
        int pocet = 0;
        try {
           
            stmt = con.createStatement();
            String sql;
            String limit;
            if (request.getParameter("strana") != null) {
                int strana = Integer.parseInt(request.getParameter("strana"));
                int pocetpol;
                if (session.getAttribute("pocet_poloziek") != null) {
                    pocetpol = (Integer) session.getAttribute("pocet_poloziek");
                } //pocet poloziek na stranu pre neregistrovaných
                else {
                    pocetpol = 10;
                }
                limit = (strana * pocetpol) - pocetpol + ", " + pocetpol;
            } else {
                int pocetpol;
                if (session.getAttribute("pocet_poloziek") != null) {
                    pocetpol = (Integer) session.getAttribute("pocet_poloziek");
                } //pocet poloziek na stranu pre neregistrovaných
                else {
                    pocetpol = 10;
                }
                limit = "0," + pocetpol;
            }

            if (podkategoria != null) {
                sql = "Select * from inzerat join mesto on inzerat.id_mesta = mesto.id_mesta where id_podkategorie=" + podkategoria + " AND viditelny = 1 order by datum_pridania desc limit " + limit;
            } else {
                sql = "Select * from inzerat join mesto on inzerat.id_mesta = mesto.id_mesta where viditelny = 1 order by datum_pridania desc limit " + limit;

            }
            vypisStranky(request.getParameter("podkategoria"), request);
            rs = stmt.executeQuery(sql);
            rs.last();
            int in = rs.getRow();
            rs.beforeFirst();
            while (rs.next()) {
                Inzerat i = new Inzerat();
                i.setCena(rs.getInt("cena"));
                i.setDatum_pridania(rs.getTimestamp("datum_pridania"));
                i.setEmail(rs.getString("email"));
                i.setHeslo(rs.getString("heslo"));
                i.setId_inzeratu(rs.getInt("id_inzeratu"));
                i.setId_usera(rs.getInt("id_usera"));
                i.setMeno(rs.getString("meno"));
                i.setNazov_inzeratu(rs.getString("nazov_inzeratu"));
                i.setText_inzeratu(rs.getString("text_inzeratu"));
                i.setPocet_zobrazeni(rs.getInt("pocet_zobrazeni"));
                i.setId_mesta(rs.getInt("id_mesta"));
                i.setMesto(rs.getString("nazov_mesta"));
                i.setPsc(rs.getString("psc"));
                VypisInzerat(i, response);
                pocet++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (pocet * 205 < 2050) {
            return 2050 + 100;
        } else {
            return pocet * 205 + 100;
        }
    }

    private synchronized void VypisInzerat(Inzerat inzerat, HttpServletResponse response) {
        try {
            SimpleDateFormat s = new SimpleDateFormat("dd.MM.YYYY");
            //TODO: pridať možnosť ponuka/dopyt
            out.println("<div class=\"inzerat\">");
            //out.println("<img src= \"img/oddelovac_hore.png\" />");
            out.println("<table width=\"590\" border=\"0\">");
            out.println("<tr>");
            out.println("<td colspan=\"2\"><a href=\"./inzerat.jsp?c=" + inzerat.getId_inzeratu() + "\" >" + inzerat.getNazov_inzeratu() + "</a>  - " + s.format(inzerat.getDatum_pridania()) + "</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td rowspan=\"3\" width=\"100\" >" + "<a href=\"./inzerat.jsp?c=" + inzerat.getId_inzeratu() + " \">"+"<img class=\"obrazok\" src=\"./displayImage?id=" + inzerat.getId_inzeratu() + "\" height=\"100\"/></a>" + "</td>");
            if(inzerat.getText_inzeratu().length()>150){
                out.println("<td rowspan=\"2\">" + inzerat.getText_inzeratu().substring(0, 150)+"..." + "</td>");
            }else{
            out.println("<td rowspan=\"2\">" + inzerat.getText_inzeratu() + "</td>");
            }
            out.println("</tr>");
            out.println("<tr>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Cena: " + inzerat.getCena() + " €" + "<br/>");
            out.println("" + inzerat.getMesto() + "\n" + inzerat.getPsc() + "</td>");
            out.println("</tr>");
            out.println("<tr>");
            out.println("<td>Zobrazenia: " + inzerat.getPocet_zobrazeni() + "</td>");
            out.println("<td>moznosti inzeratu</td>");
            out.println("</tr>");
            out.println("</table>");
            out.println("</div>");
            //out.println("<img src= \"img/oddelovac_dole.png\" />");
            out.println("<br/>");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        try {
            session = request.getSession(true);
            VypisInzeraty(request, response);
            vypisStranky(request.getParameter("podkategoria"), request);
            out.println("<br/><br/>");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    
    
    private void vypisStranky(String podkategoria, HttpServletRequest request) {
        String sql;
        if (podkategoria != null) {
            sql = "select count(id_inzeratu) as pocet from inzerat where id_podkategorie=" + podkategoria + " AND viditelny = 1";
        } else {
            sql = "select count(id_inzeratu) as pocet from inzerat where viditelny = 1";
        }
        try {
            ResultSet result;
            stmt = con.createStatement();
            result = stmt.executeQuery(sql);
            result.next();
            int pocetinzeratov = result.getInt("pocet");
            int pocet_poloziek;
            //System.out.println(session.getAttribute("id_usera") + ":" + "pocet_poloziek: " + session.getAttribute("pocet_poloziek"));
            if (session.getAttribute("pocet_poloziek") != null) {
                pocet_poloziek = (Integer) session.getAttribute("pocet_poloziek");
            } //pocet poloziek na stranu pre neregistrovaných
            else {
                pocet_poloziek = 10;
            }
            int pocetstranok = pocetinzeratov / pocet_poloziek;
            out.println("<div align=\"center\" class=\"stranky\" >");
            if (pocetinzeratov % pocet_poloziek > 0) {
                pocetstranok++;
            }
            Enumeration menap = request.getParameterNames();
                String parametre = "";
                while(menap.hasMoreElements()){
                    String meno = (String)menap.nextElement();
                    parametre = parametre + "&amp;"+meno+"=";
                    for(int k=0;k<request.getParameterValues(meno).length;k++){
                        parametre = parametre + request.getParameterValues(meno)[k];
                    }
                }
                if(request.getParameter("strana")!=null){
                    parametre = "";
                }
                System.out.println(parametre);
            for (int i = 1; i <= pocetstranok; i++) {
                String values = "";
                if (request.getParameter("podkategoria") != null) {
                    values = "&podkategoria=" + request.getParameter("podkategoria");
                }
                if (request.getParameter("kategoria") != null) {
                    values = "&kategoria=" + request.getParameter("kategoria");
                }
                StringBuilder sb = new StringBuilder();
                
                sb.append("<a href = \"./inzeraty.jsp?strana=" + i +  parametre + "\"  ");
                if (request.getParameter("strana") != null) {
                    if (Integer.parseInt(request.getParameter("strana")) == i) {
                        sb.append("class=\"stranka\"  >" + i + "</a>");
                    } else {
                        sb.append(" >" + i + "</a>");
                    }
                } else {
                    if (i == 1) {
                        sb.append("class=\"stranka\" >" + i + "</a>");
                    } else {
                        sb.append(">" + i + "</a>");
                    }
                }
                out.println(sb.toString());

            }

            out.println("</div>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
